<template>
    <div class="image-gallery-container">
      <h1 class="gallery-title">---------- 图 片 资 料 ----------</h1>
  
      <div class="image-grid">
        <!-- 现有图片 -->
        <div 
          v-for="(imageUrl, index) in visibleImages" 
          :key="index" 
          class="image-item"
        >
          <img 
            :src="imageUrl" 
            :alt="'图片' + (index + 1)" 
            class="gallery-image" 
            loading="lazy"
            @click="openLightbox(index)"
          >
          <!-- 图片操作按钮 -->
          <div class="image-actions">
            <button class="action-btn replace-btn" @click.stop="replaceImage(index)">
              <el-icon><Refresh /></el-icon>
            </button>
            <button 
              class="action-btn delete-btn" 
              @click.stop="deleteImage(index)"
              :disabled="Store.$state.AITeach.Step5.content.length <= 1"
            >
              <el-icon><Delete /></el-icon>
            </button>
          </div>
        </div>
  
        <!-- 添加图片按钮 -->
        <div class="image-item add-image" @click="openUploadDialog(null)">
          <el-icon class="add-icon"><Plus /></el-icon>
          <span>添加图片</span>
        </div>
      </div>
      <h1 class="gallery-title">---------- 图 片 资 料 ----------</h1>
  
      <!-- 图片预览弹窗 -->
      <div class="lightbox" v-if="lightboxVisible" @click.self="closeLightbox">
        <button class="close-btn" @click="closeLightbox">&times;</button>
        <button class="nav-btn prev-btn" @click.stop="prevImage">&lt;</button>
        <div class="lightbox-content">
          <img 
            :src="Store.$state.AITeach.Step5.content[currentIndex]" 
            :alt="'预览图片'" 
            class="lightbox-image"
          >
          <div class="lightbox-actions">
            <el-button type="primary" @click.stop="openUploadDialog(currentIndex)">
              替换图片
            </el-button>
            <el-button 
              type="danger" 
              @click.stop="deleteImage(currentIndex)"
              :disabled="Store.$state.AITeach.Step5.content.length <= 1"
            >
              删除图片
            </el-button>
          </div>
        </div>
        <button class="nav-btn next-btn" @click.stop="nextImage">&gt;</button>
      </div>
  
      <!-- 图片上传对话框 -->
      <el-dialog v-model="uploadDialogVisible" title="上传图片" width="500px" :close-on-click-modal="false">
        <el-upload
          class="upload-demo"
          drag
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
          :before-upload="beforeImageUpload"
          accept="image/jpeg,image/png,image/gif,image/webp"
          :disabled="uploading"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            拖拽图片到此处或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 JPG/PNG/GIF/WEBP 格式图片，单张不超过 5MB
            </div>
          </template>
        </el-upload>
        <template #footer>
          <el-button @click="cancelUpload" :disabled="uploading">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmUpload"
            :loading="uploading"
            :disabled="!selectedFile || uploading"
          >
            {{ uploading ? '上传中...' : '确认上传' }}
          </el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, onUnmounted, computed } from 'vue';
  import { useCounterStore } from '@/stores/counter';
  import { Refresh, Delete, Plus, UploadFilled } from '@element-plus/icons-vue';
  import axios from 'axios';
  import { ElMessage, ElLoading } from 'element-plus';
  
  // 定义Store中Step5的类型
  interface Step5State {
    state: number;
    content: string[];
  }
  
  const Store = useCounterStore() as {
    $state: {
      AIClassQuestion: string;
      AITeach: {
        Step5: Step5State;
      };
    };
    addAIteachStep5: (images: string[]) => void;
  };
  
  // 状态变量
  const lightboxVisible = ref(false);
  const currentIndex = ref(0);
  const uploadDialogVisible = ref(false);
  const selectedFile = ref<File | null>(null);
  const replaceIndex = ref<number | null>(null);
  const uploading = ref(false);
  
  // 计算属性
  const visibleImages = computed(() => {
    return Store.$state.AITeach.Step5.content;
  });
  
  // 方法定义
  const openUploadDialog = (index: number | null) => {
    replaceIndex.value = index;
    selectedFile.value = null;
    uploadDialogVisible.value = true;
  };
  
  const handleFileChange = (uploadFile: any) => {
    if (!uploadFile || !uploadFile.raw) {
      ElMessage.error('无效的文件');
      return;
    }
    
    if (!beforeImageUpload(uploadFile.raw)) {
      return;
    }
  
    selectedFile.value = uploadFile.raw;
  };
  
  const cancelUpload = () => {
    if (!uploading.value) {
      selectedFile.value = null;
      uploadDialogVisible.value = false;
    }
  };
  
  const beforeImageUpload = (file: File) => {
    const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    const isImage = validTypes.includes(file.type);
    const isLt5M = file.size / 1024 / 1024 < 5;
  
    if (!isImage) {
      ElMessage.error('只支持JPG/PNG/GIF/WEBP格式的图片!');
      return false;
    }
    if (!isLt5M) {
      ElMessage.error('图片大小不能超过5MB!');
      return false;
    }
    return true;
  };
  
  const confirmUpload = async () => {
    if (!selectedFile.value) {
      ElMessage.warning('请先选择图片文件');
      return;
    }
  
    // 严格验证文件对象
    if (!(selectedFile.value instanceof Blob)) {
      ElMessage.error('无效的文件对象');
      return;
    }
  
    const loading = ElLoading.service({
      lock: true,
      text: '图片上传中...',
      background: 'rgba(0, 0, 0, 0.7)',
    });
  
    uploading.value = true;
    
    try {
      // 创建对象URL
      const objectUrl = URL.createObjectURL(selectedFile.value);
      
      // 创建新数组确保响应式更新
      const newImages = [...Store.$state.AITeach.Step5.content];
      
      if (replaceIndex.value !== null) {
        // 替换前释放旧URL
        if (newImages[replaceIndex.value]?.startsWith('blob:')) {
          URL.revokeObjectURL(newImages[replaceIndex.value]);
        }
        newImages[replaceIndex.value] = objectUrl;
        ElMessage.success('图片替换成功');
      } else {
        newImages.push(objectUrl);
        ElMessage.success('图片添加成功');
      }
      
      // 更新Store
      Store.addAIteachStep5(newImages);
      
      uploadDialogVisible.value = false;
      selectedFile.value = null;
    } catch (error) {
      console.error('创建对象URL失败:', error);
      ElMessage.error('图片处理失败，请重试');
    } finally {
      loading.close();
      uploading.value = false;
    }
  };
  
  const replaceImage = (index: number) => {
    openUploadDialog(index);
  };
  
  const deleteImage = (index: number) => {
    if (Store.$state.AITeach.Step5.content.length <= 1) {
      ElMessage.warning('至少需要保留一张图片');
      return;
    }
    
    // 释放被删除图片的URL
    const url = Store.$state.AITeach.Step5.content[index];
    if (url?.startsWith('blob:')) {
      URL.revokeObjectURL(url);
    }
    
    const newImages = [...Store.$state.AITeach.Step5.content];
    newImages.splice(index, 1);
    Store.addAIteachStep5(newImages);
    
    ElMessage.success('图片删除成功');
    
    if (lightboxVisible.value && currentIndex.value >= Store.$state.AITeach.Step5.content.length) {
      closeLightbox();
    }
  };
  
  const openLightbox = (index: number) => {
    currentIndex.value = index;
    lightboxVisible.value = true;
    document.body.style.overflow = 'hidden';
  };
  
  const closeLightbox = () => {
    lightboxVisible.value = false;
    document.body.style.overflow = '';
  };
  
  const nextImage = () => {
    currentIndex.value = (currentIndex.value + 1) % Store.$state.AITeach.Step5.content.length;
  };
  
  const prevImage = () => {
    currentIndex.value = (currentIndex.value - 1 + Store.$state.AITeach.Step5.content.length) % Store.$state.AITeach.Step5.content.length;
  };
  
  // 初始化加载图片
  onMounted(async () => {
    if (Store.$state.AITeach.Step5.content.length === 0) {
      try {
        const response = await axios({
          url: "https://m1.apifoxmock.com/m1/5997017-0-default/teacher/design/pictures",
          method: "GET",
          params: {
            text: Store.$state.AIClassQuestion
          }
        });
        
        if (response.data.code === 1) {
          const images = Array.isArray(response.data.data.imgUrl) 
            ? response.data.data.imgUrl 
            : [response.data.data.imgUrl];
          Store.addAIteachStep5(images.filter((img: unknown) => typeof img === 'string'));
        } else {
          console.error("获取数据失败:网络错误");
        }
      } catch (error) {
        console.error("获取数据失败:", error);
      }
    }
  });
  
  // 键盘事件监听
  const handleKeyDown = (e: KeyboardEvent) => {
    if (!lightboxVisible.value) return;
  
    if (e.key === 'Escape') {
      closeLightbox();
    } else if (e.key === 'ArrowRight') {
      nextImage();
    } else if (e.key === 'ArrowLeft') {
      prevImage();
    }
  };
  
  onMounted(() => {
    document.addEventListener('keydown', handleKeyDown);
  });
  
  // 清理工作
  onUnmounted(() => {
    // 清理所有blob URL
    Store.$state.AITeach.Step5.content.forEach(url => {
      if (url?.startsWith('blob:')) {
        try {
          URL.revokeObjectURL(url);
        } catch (e) {
          console.warn('释放Blob URL失败:', e);
        }
      }
    });
    document.removeEventListener('keydown', handleKeyDown);
  });
  </script>
  
  <style scoped>
  /* 保持原有样式不变 */
  .image-gallery-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .gallery-title {
    text-align: center;
    font-weight: 1000;
    font-size: 25px;
    margin-bottom: 10px;
    color: #409EFF;
  }
  
  .image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    padding: 10px;
  }
  
  .image-item {
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    aspect-ratio: 4/3;
    background-color: #f5f5f5;
  }
  
  .image-item:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
  }
  
  .gallery-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    transition: opacity 0.3s ease;
    cursor: pointer;
  }
  
  .gallery-image:hover {
    opacity: 0.9;
  }
  
  .image-actions {
    position: absolute;
    top: 10px;
    right: 10px;
    display: flex;
    gap: 8px;
    opacity: 0;
    transition: opacity 0.3s ease;
  }
  
  .image-item:hover .image-actions {
    opacity: 1;
  }
  
  .action-btn {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s ease;
    background-color: rgba(255, 255, 255, 0.8);
    color: #333;
  }
  
  .replace-btn:hover {
    background-color: rgba(64, 158, 255, 0.8);
    color: white;
  }
  
  .delete-btn:hover {
    background-color: rgba(245, 108, 108, 0.8);
    color: white;
  }
  
  .delete-btn:disabled {
    background-color: rgba(200, 200, 200, 0.8);
    cursor: not-allowed;
  }
  
  .add-image {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f0f2f5;
    border: 2px dashed #c0c4cc;
    cursor: pointer;
    transition: all 0.3s ease;
    color: #909399;
  }
  
  .add-image:hover {
    border-color: #409EFF;
    background-color: #ecf5ff;
  }
  
  .add-icon {
    font-size: 36px;
    margin-bottom: 8px;
  }
  
  .lightbox {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.9);
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .lightbox-content {
    max-width: 90%;
    max-height: 90%;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .lightbox-image {
    max-height: 80vh;
    max-width: 100%;
    object-fit: contain;
  }
  
  .lightbox-actions {
    margin-top: 20px;
    display: flex;
    gap: 15px;
  }
  
  .close-btn {
    position: absolute;
    top: 20px;
    right: 20px;
    background: none;
    border: none;
    color: white;
    font-size: 30px;
    cursor: pointer;
    z-index: 1001;
  }
  
  .nav-btn {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background: rgba(255, 255, 255, 0.3);
    border: none;
    color: white;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    font-size: 24px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: background 0.3s ease;
  }
  
  .nav-btn:hover {
    background: rgba(255, 255, 255, 0.5);
  }
  
  .prev-btn {
    left: 20px;
  }
  
  .next-btn {
    right: 20px;
  }
  
  .upload-demo {
    text-align: center;
  }
  
  .el-icon--upload {
    font-size: 67px;
    color: var(--el-color-primary);
    margin: 40px 0 16px;
    line-height: 50px;
  }
  
  .el-upload__text {
    color: var(--el-text-color-regular);
    font-size: 14px;
    text-align: center;
  }
  
  .el-upload__text em {
    color: var(--el-color-primary);
    font-style: normal;
  }
  
  .el-upload__tip {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 7px;
  }
  
  @media (max-width: 768px) {
    .image-grid {
      grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    }
    
    .nav-btn {
      width: 40px;
      height: 40px;
      font-size: 20px;
    }
    
    .lightbox-actions {
      flex-direction: column;
      gap: 10px;
    }
  }
  
  @media (max-width: 480px) {
    .image-grid {
      grid-template-columns: 1fr;
    }
    
    .gallery-title {
      font-size: 20px;
    }
  }
  </style>